/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package au.com.domlogic.pvc.core.servlet;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Domenic Figliomeni
 *
 * This filter wraps the response with a LocalredirectionResponseWrapper.
 * This allows the developer to easily redirect browsers to local resource
 * by handling the url construction in the response.  The author of web.xml
 * can safely wrap all responses for simplicity or selectively wrap only as
 * required to save unneccessary processing.
 *
 */
public class LocalRedirectionResponseFilter implements Filter {

    private FilterConfig filterConfig;

    @Override
    public void init(FilterConfig filterConf) throws ServletException {
        this.filterConfig = filterConf;
    }

    @Override
    public void doFilter(ServletRequest request,
            ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        if (response instanceof LocalRedirectionResponseWrapper) {
            chain.doFilter(request, response);
        } else if (response instanceof HttpServletResponse) {
            LocalRedirectionResponseWrapper wrappedResponse =
                    new LocalRedirectionResponseWrapper((HttpServletResponse) response);
            chain.doFilter(request, wrappedResponse);
        } else {
            throw new ServletException("The response was not a HttpServletResponse.  It was a\t" + response.getClass().getName());
        }
    }

    @Override
    public void destroy() {
        this.filterConfig = null;
    }

    public FilterConfig getFilterConfig() {
        return filterConfig;
    }

    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }
}
